from django.db import models
from django.utils import timezone

from core.models import BaseModel

from datetime import datetime
from decouple import config
import requests


# Create your models here.
class AccessToken(BaseModel):

    appid           = models.CharField(unique=True, max_length = 128, null = True, blank = True)

    token           = models.CharField(max_length = 128, null = True, blank = True)

    def _obtain_token(self):
        print('准备获取微信access_token')
        url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={config("WEIXIN_APP_ID")}&secret={config("WEIXIN_APP_SECRET")}'
        r = requests.get(url).json()
        print('获取微信access_token', f"{r['access_token'][:10]}...{r['access_token'][-10:]}")
        return r['access_token']

    def get_valid_token(self):
        instance, created = AccessToken.objects.get_or_create(appid = config("WEIXIN_APP_ID"))
        delta = datetime.now(timezone.utc) - instance.update_time
        if delta.total_seconds() > 7200 or instance.token is None:
            print('微信token已过期，重新获取', delta.total_seconds())
            instance.token = self._obtain_token()
            instance.save()
            return instance.token
        return instance.token

    class Meta:
        verbose_name = "微信Token"
        verbose_name_plural = "微信Token"


class Block(BaseModel):
    account         = models.ForeignKey('account.Account', on_delete=models.SET_NULL, null = True, blank = True)
    address         = models.CharField('IP地址', max_length = 128, null = True, blank = True)

    class Meta:
        verbose_name = "黑名单"
        verbose_name_plural = "黑名单"